package com.txc.common.global.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.logging.Logger;

/**
 * @ClassName: RedissonConfig
 * @Author: TXC
 * @Date: 2022-08-01 15:11
 **/
@Configuration
public class RedissonConfig {
    @Resource
    private RedisProperties redisProperties;

    private static final Logger logger = Logger.getLogger(String.valueOf(RedissonConfig.class));

    /**
     * 单机模式配置
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try {
            Config config = new Config();
            config.useSingleServer().setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                    .setDatabase(redisProperties.getDatabase()).setPassword(redisProperties.getPassword())
                    .setUsername(redisProperties.getUsername());
            config.setCodec(new JsonJacksonCodec());
            RedissonClient redissonClient = Redisson.create(config);
            logger.info("==========Redisson配置完成！");
            return redissonClient;
        } catch (Exception e) {
            logger.info("==========Redisson配置失败！" + e.getMessage());
            return null;
        }
    }

    /**
     * 构建Redisson缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedissonClient redisson) {
        return new RedissonSpringCacheManager(redisson);
    }
}
